#include "lab4.h"

// see lab4.h
int main (int argc, char* argv[]) {
    
    if (argc != 2) {
        cout << "ERROR: A single file must be specified.  Usage: matrix_calc <filename>";
        exit(EXIT_FAILURE);
    }
    
    Calc<int>* calc = new Calc<int>();
    readFile(argv[1], calc);
    calc->execute();
    
    // Cleanup and exit
    delete calc;
}

// see lab4.h
template <class T>
void readFile(const char* filename, Calc<T>* calc) {
    ifstream fileS;
    fileS.open(filename);
    if (fileS.is_open()) {

        // Read the file, checking the formatting
        string line;
        stringstream lineS;
        getline(fileS, line);
        lineS << line;

        // Read the size of the matrices
        int matrixSize = -1;
        lineS >> matrixSize;

        // We now assume that the next n lines contain n elements.
        Matrix<T>* a = new Matrix<T>(matrixSize);
        for (int i=0; i<matrixSize; i++) {
            getline(fileS, line);
            lineS << line;
            lineS << " ";
        }
        a->parseLines(&lineS);
        cout << "Matrix A is: \n" << *a;
        calc->setMatrixA(a);

        // Read operator and confirm buf is 'operator'
        lineS.clear();
        getline(fileS, line);
        lineS << line;
        string buf;
        lineS >> buf;
        if (buf.compare("op") != 0) {
            cout << "Error reading file, expected OP line, was: " << buf << "\n";
            fileS.close();
            exit(EXIT_FAILURE);
        }
        int op = -1;
        lineS >> op;
        calc->setOperation(op);
        
        // If op is 1, 2 or 3 read the second matrix; if it's 4 or above 
        // there are no other lines
        if (op < 4) {
            Matrix<T>* b = new Matrix<T>(matrixSize);        
            for (int i=0; i < matrixSize; i++) {
                getline(fileS, line);
                lineS << line;
                lineS << " ";
            }
            b->parseLines(&lineS);
            cout << "Matrix B is: \n" << *b;
            calc->setMatrixB(b);            
        }

        fileS.close();        
    } else {
        cout << "ERROR: Unable to open file: " << filename << ".  Aborting.";
        exit(EXIT_FAILURE);
    }    
}
